import { useMemberStore } from './../stores/modules/member'
// 请求基地址
const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
// 配置拦截器
const httpInterceptor = {
  // 拦截前出发
  invoke(options: UniApp.RequestOptions) {
    console.log(options)
    // 1. 非 http 开头需拼接地址
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }
    options.timeout = 100000
    // 请求头
    options.header = {
      // 防止被复制
      ...options.header,
      'source-client': 'miniapp',
    }
    //添加 token 请求头标识
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }
    console.log(options)
  },
}
interface Data<T> {
  code: string
  msg: string
  result: T
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)
export const http = <T>(option: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...option,
      success(result) {
        if (result.statusCode >= 200 && result.statusCode < 300) {
          resolve(result.data as Data<T>)
        } else if (result.statusCode === 401) {
          const memberSore = useMemberStore()
          memberSore.clearProfile()
          uni.navigateTo({
            url: '/pages/login/login',
          })
        } else {
          uni.showToast({
            title: (result.data as Data<T>).msg || '请求错误',
            icon: 'none',
          })
          reject(result)
        }
      },
      fail(err) {
        uni.showToast({
          title: '网络错误，换个网络试下',
          icon: 'none',
        })
      },
    })
  })
}
